package com.fstec.ks.master.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.hyperic.sigar.NetInterfaceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fstec.ks.master.MasterEngine;
import com.fstec.ks.master.bean.ServerInfoBean;
import com.fstec.ks.master.process.AuthFileProcess;
import com.sinotn.error.MessageException;
import com.sinotn.sigar.SigarUtils;
import com.sinotn.task.TaskServer;
import com.sinotn.web.ResponseUtil;

/**
 * 授权配置请求处理
 * @Title AuthAction.java
 * @Package com.fstec.ks.master.action
 * @Description 
 * Copyright: Copyright (c) 2023
 * Company:广东峰上科技有限公司
 * 
 * @author <a href="mailto:xieqj@fstec.com">谢启进</a>
 * @date 2023年10月9日 下午5:38:16
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/R/auth")
public class AuthAction {
	@Autowired
	private MasterEngine masterEngine;
	@Autowired
	private TaskServer taskServer;
	/*
	 * 打开授权配置查看界面
	 */
	@RequestMapping(value = "/view.jspx")
	public String view(HttpServletRequest request,ModelMap model){
		ServerInfoBean serverInfoBean=this.masterEngine.getServerInfo();
		model.put("ServerInfo", serverInfoBean);
		List<NetInterfaceConfig> list=SigarUtils.getNetInterfaceConfigs();
		
		if(list!=null&&list.size()>0){
			NetInterfaceConfig config;
			int size=list.size();
			ArrayList<String> ipAddrs=new ArrayList<String>(size);
			for(int i=0;i<size;i++){
				config=list.get(i);
				ipAddrs.add(config.getAddress());
			}
			model.put("IpAddrs", ipAddrs);
		}
		return "setting/authorization";
	}
	
	/*
	 * 刷新授权号
	 */
	@RequestMapping(value = "/refresh.jspx")
	public void refresh(HttpServletRequest request,HttpServletResponse response){
		String newAuthCode=this.masterEngine.refreshAuth();
		StringBuilder sb=new StringBuilder();
		sb.append("{\"state\":0,\"data\":\"").append(newAuthCode).append("\"}");
		ResponseUtil.renderJson(response, sb.toString());
	}
	
	/*
	 * 下载授权文件
	 */
	@RequestMapping(value = "/downAuth.jspx")
	public void downAuth(HttpServletRequest request,HttpServletResponse response){
		String ipAddr=request.getParameter("ipAddr");
		if(StringUtils.isEmpty(ipAddr)){
			throw new MessageException("服务Ip参数不能为空");
		}
		AuthFileProcess process=new AuthFileProcess(ipAddr);
		this.taskServer.putAsyncTask(process, true);
		StringBuilder sb=new StringBuilder();
		sb.append("{\"state\":0,\"data\":\"").append(process.getId()).append("\"}");
		ResponseUtil.renderJson(response, sb.toString());
	}
}
